﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Security.Cryptography;
using System.Web.Security;
using System.Data;
using SQLHelper;
public partial class admin_Me : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        bind();
    }

    protected void UpdateProfile(object sender, EventArgs e)
    {
        // 检查是否存在文件
        if (FileUpload1.HasFile)
        {
            // 检查是否为图片
            string ImgExtension = Path.GetExtension(FileUpload1.FileName);
            if (isImg(ImgExtension))
            {
                // 检查图片大小，控制在1024k以内
                if(FileUpload1.PostedFile.ContentLength < 1048576)
                {
                    string filepath = "/Upload/";
                    string virpath = filepath + CreatePasswordHash(FileUpload1.FileName, 4) + ImgExtension;//虚拟路径
                    string mappath = Server.MapPath(virpath);//转换成物理路径
                    // 保存图片
                    FileUpload1.PostedFile.SaveAs(mappath);

                    string name = TextBox1.Text.ToString().Trim();
                    string education = TextBox2.Text.ToString().Trim();
                    string location = TextBox3.Text.ToString().Trim();
                    string notes = TextBox4.Text.ToString().Trim();
                    string sql = "update users set name = '" +
                        name + "', photo = '" +
                        virpath + "', education = '" +
                        education + "', location = '" +
                        location + "', notes = '" +
                        notes + "' where id = " +
                        Master.UserID;
                    DB.GetDataNoQuery(sql);
                    DB.ColseSqlCon();
                    Response.Redirect("~/admin/Me.aspx");
                }
                else
                {
                    Label1.Text = "图片应该小于1M";
                }
            }
            else
            {
                Label1.Text = "选择的文件类型不正确，请重新选择";
            }
        }
        else
        {
            Label1.Text = "请选择图片";
        }
    }

    protected void UpdatePW(object sender, EventArgs e)
    {
        string ComparePW = Session["password"].ToString();
        string OldPW = TextBox5.Text.ToString().Trim();
        string NewPW = TextBox7.Text.ToString().Trim();
        if(ComparePW == FormsAuthentication.HashPasswordForStoringInConfigFile(OldPW, "MD5"))
        {
            string md5Password = FormsAuthentication.HashPasswordForStoringInConfigFile(NewPW, "MD5");
            string sql = "update users set password = '" + md5Password + "' where id = " + Master.UserID;
            DB.GetDataNoQuery(sql);
            DB.ColseSqlCon();
            // 修改成功退出用户重新登录
            if (HttpContext.Current.Request.Cookies["NOAP_USER_ACCOUNT"] != null)
            {
                HttpCookie UserAccountCookie = HttpContext.Current.Request.Cookies["NOAP_USER_ACCOUNT"];
                UserAccountCookie.Expires = DateTime.Now.AddDays(-2);
                HttpContext.Current.Response.Cookies.Add(UserAccountCookie);
            }
            // 使cookie过期，删除cookie，不用关闭浏览器
            HttpContext.Current.Session["email"] = null;
            HttpContext.Current.Session["password"] = null;
            Response.Redirect("~/admin/Me.aspx");
        }
        else
        {
            Label2.Text = "旧密码输入与当前账户密码不一致";
        }
    }

    string CreateSalt(int saltLenght)
    {
        //生成一个加密的随机数
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        byte[] buff = new byte[saltLenght];
        rng.GetBytes(buff);
        //返回一个Base64随机数的字符串
        return Convert.ToBase64String(buff);
    }

    string CreatePasswordHash(string pwd, int saltLenght)
    {
        string strSalt = CreateSalt(saltLenght);
        //把密码和Salt连起来
        string saltAndPwd = String.Concat(pwd, strSalt);
        //对密码进行哈希
        string hashenPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1");
        //转为小写字符并截取前16个字符串
        hashenPwd = hashenPwd.ToLower().Substring(0, 16);
        //返回哈希后的值
        return hashenPwd;
    }

    bool isImg(string str)
    {
        bool isImg = false;
        string strLow = str.ToLower();
        string[] arr = new string[3] { ".jpg", ".png", ".jpeg" };
        for (int i = 0; i < arr.Length; i++)
        {
            if(strLow == Convert.ToString(arr[i]))
            {
                isImg = true;
                break;
            }
        }
        return isImg;
    }

    void bind()
    {
        string sql = "select c.*,n.title from comments c left join news n on c.news_id = n.id where c.user_id = " + Master.UserID;
        DataSet res = DB.GetDataWithQuerySecond(sql, "news");
        ListView1.DataSource = res;
        ListView1.DataBind();
        DB.ColseSqlCon();
    }
}